<script setup>
import { ref, reactive, getCurrentInstance } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { useMyToastStore } from "@/store/myToast";

const myToast = useMyToastStore();
const instance = getCurrentInstance();
const util = instance?.proxy?.$util;
const request = instance?.proxy?.$request;

let userInfo = uni.getStorageSync("userInfo") || {};
onShow(() => {
  userInfo = uni.getStorageSync("userInfo") || {};
});
let isLogin = ref(false);
let scoresList = reactive([]);
let headerHeight = ref(0);
let creditsCount = ref(0);
let gpa = ref(0);
const query = uni.createSelectorQuery().in(instance);
query
  .select(".header-navbar")
  .boundingClientRect((data) => {
    headerHeight.value = data.height;
    console.log(data);
  })
  .exec();
const getScoresList = async (year, term) => {
  isLogin.value = true;
  scoresList = [];
  console.log(year, term);
  try {
    if (term == 1) {
      term = 3;
    } else if (term == 2) {
      term = 12;
    } else {
      term = 16;
    }
    const result = await request.post("scoresList", {
      year,
      term,
      cookie: userInfo.cookie,
      account: userInfo.account,
    });
    console.log(result);
    if (result.status == 200) {
      if (result.data.items.length == 0) {
        myToast.params = {
          type: "warning",
          message: "无结果，请尝试更换学期",
        };
      } else {
        scoresList = result.data.items;
        creditsCount.value = 0;
        gpa.value = 0;
        let creditsSum = 0;
        let itemCredits = 0;
        let itemGpa = 0;
        await new Promise((resolve, reject) => {
          scoresList.forEach((item) => {
            if (item.kcxzdm != "02") {
              itemCredits = Number(item.bfzcj) * Number(item.xf) + itemCredits;
              creditsSum = Number(item.xf) + creditsSum;
              itemGpa = item.jd * item.xf + itemGpa;
            }
            resolve();
          });
        });
        creditsCount.value = (itemCredits / creditsSum).toFixed(2);
        gpa.value = (itemGpa / creditsSum).toFixed(2);
      }
      isLogin.value = false;
    } else {
      myToast.params = {
        type: "error",
        message: "查询失败，请尝试重新登录",
        complete() {
          util.jumpPage("/pages/user/login");
        },
      };
      isLogin.value = false;
    }
  } catch (error) {
    console.log(error);
    myToast.params = {
      type: "error",
      message: "查询遇到问题，请稍后重试",
    };
    isLogin.value = false;
  }
};
let newInquiry = ref(
  `${new Date().getFullYear() - 1}-${new Date().getFullYear()} 第一学期`
);
let indexTap = ref(0);
const handleInquiryResults = () => {
  uni.showActionSheet({
    itemList: [
      `${new Date().getFullYear() - 1}-${new Date().getFullYear()} 第一学期`,
      `${new Date().getFullYear() - 1}-${new Date().getFullYear()} 第二学期`,
      `${new Date().getFullYear()}-${new Date().getFullYear() + 1} 第一学期`,
    ],
    success: ({ tapIndex }) => {
      indexTap.value = tapIndex;
      if (tapIndex == 0) {
        newInquiry.value = `${
          new Date().getFullYear() - 1
        }-${new Date().getFullYear()} 第一学期`;
      } else if (tapIndex == 1) {
        newInquiry.value = `${
          new Date().getFullYear() - 1
        }-${new Date().getFullYear()} 第二学期`;
      } else {
        newInquiry.value = `${new Date().getFullYear()}-${
          new Date().getFullYear() + 1
        } 第一学期`;
      }
    },
  });
};
const handleGetScoresList = () => {
  if (indexTap.value == 0) {
    getScoresList(new Date().getFullYear() - 1, 1);
  } else if (indexTap.value == 1) {
    getScoresList(new Date().getFullYear() - 1, 2);
  } else {
    getScoresList(new Date().getFullYear(), 1);
  }
};
</script>

<template>
  <view class="scores-box">
    <myToast></myToast>
    <view class="header-navbar">
      <u-navbar autoBack placeholder leftIconSize="38">
        <template #center>
          <text class="text-16 text-bold-700">我的成绩</text>
        </template>
      </u-navbar>
    </view>
    <view
      class="scores-header flex align-center justify-between"
      :style="{ top: `${headerHeight}px` }"
      v-if="scoresList.length > 0"
    >
      <view class="header-item">
        <text>学分加权平均分 {{ creditsCount }}</text>
      </view>
      <view class="header-item">
        <text>平均绩点 {{ gpa }}</text>
      </view>
      <view class="header-item">
        <text>不含公共课</text>
      </view>
    </view>
    <view class="null-box" v-if="scoresList.length == 0">
      <image src="/static/sousuo.png" mode="widthFix" />
    </view>
    <view class="scores-list" v-else>
      <view
        class="scores-item"
        v-for="(item, index) in scoresList"
        :key="index"
      >
        <view
          class="item-box flex align-center justify-between"
          :class="item.bfzcj < 60 ? 'item-box-err' : ''"
        >
          <view>
            <view class="course-name">
              <text class="name-text">《{{ item.kcmc }}》</text>
            </view>
            <view
              class="course-content"
              :style="{ color: item.bfzcj < 60 ? '#873635' : '#31633b' }"
            >
              <text class="teacher-name"
                >教师: {{ item.tjrxm ? item.tjrxm : "无" }}</text
              >
              <text class="count-num">学分: {{ item.xf }}</text>
              <text class="count-num">类别: {{ item.kclbmc }}</text>
            </view>
          </view>
          <view class="score-num">
            <text :style="{ color: item.bfzcj < 60 ? '#b25755' : '#468e54' }"
              >{{ item.bfzcj }}分</text
            >
          </view>
        </view>
      </view>
    </view>
    <view class="scores-bottom-box flex align-center">
      <view
        class="bottom-text flex align-center justify-between"
        @click="handleInquiryResults"
      >
        <view>
          <view class="change-btn text-center">点击更换学期：</view>
          <view style="white-space: nowrap">{{ newInquiry }} </view>
        </view>
      </view>
      <u-button
        color="#109363"
        text="查询"
        throttleTime="1200"
        :disabled="isLogin"
        :loading="isLogin"
        @click="handleGetScoresList"
      ></u-button>
    </view>
  </view>
</template>

<style lang="scss">
.scores-box {
  .scores-header {
    position: sticky;
    top: 0;
    left: 0;
    right: 0;
    padding: 32rpx 42rpx 28rpx;
    border-bottom: 1px solid #f1f3f5;
    background-color: #fff;
    font-size: 24rpx;
    .header-item {
      white-space: nowrap;
      color: #606165;
    }
  }
  .scores-list {
    padding-bottom: 266rpx;
    .scores-item {
      margin: 42rpx 28rpx 0;
      background-color: #fff;
      border-radius: 20rpx;
      overflow: hidden;
      .item-box {
        padding: 24rpx 32rpx 24rpx;
        background-color: #f6fbf7;
        color: #468e54;
      }
      .item-box-err {
        background-color: #f9f5f5;
        color: #b25755;
      }
      .score-num {
        text {
          font-size: 38rpx;
          font-weight: 700;
        }
      }
      .course-name {
        font-size: 36rpx;
        font-weight: 700;
        .name-text {
          font-size: 32rpx;
          margin-left: -12rpx;
        }
      }
      .course-content {
        font-size: 24rpx;
        margin-top: 18rpx;
        color: #606165;
        .count-num {
          margin-left: 32rpx;
        }
      }
    }
  }
  .null-box {
    padding: 188rpx;
    image {
      height: auto;
    }
  }
  .scores-bottom-box {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 18rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
    background-color: #fff;
    border-top: 1px solid #f1f3f5;
    :deep(.u-button) {
      border-radius: 20rpx !important;
    }
    .bottom-text {
      margin-right: 28rpx;
      color: #606165;
      font-size: 24rpx;
    }
    .change-btn {
      color: #109363;
    }
  }
}
</style>
